package com.sicheng.lc.周赛.分类.图论.拓扑排序;

import java.util.ArrayDeque;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/7/5 22:09
 */
public class 参加会议的最多员工数 {
    //https://leetcode.cn/problems/maximum-employees-to-be-invited-to-a-meeting/
    public int maximumInvitations(int[] g) {
        int n = g.length;
        int[] degree = new int[n];
        for (int i : g) {
            degree[i]++;
        }
        int[] maxLength = new int[n];
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < degree.length; i++) {
            if (degree[i] == 0)
                stack.push(i);
        }

        // 拓扑排序消除环的枝叶
        while (!stack.isEmpty()) {
            int x = stack.pop();
            degree[g[x]]--;
            maxLength[x]++;
            maxLength[g[x]] = Math.max(maxLength[g[x]], maxLength[x]);
            if (degree[g[x]] == 0)
                stack.push(g[x]);
        }

        int maxRingSize = 0, maxLinkSize = 0;

        for (int i = 0; i < n; i++) {
            if (degree[i] <= 0)
                continue;

            degree[i] = -1;
            int ringSize = 1;
            for (int j = g[i]; degree[j] != -1; j = g[j]) {
                degree[j] = -1;
                ringSize++;
            }

            if (ringSize == 2) {
                maxLinkSize += maxLength[i] + maxLength[g[i]] + 2;
            } else {
                maxRingSize = Math.max(maxRingSize, ringSize);
            }
        }

        return Math.max(maxRingSize,maxLinkSize);
    }
}
